Key and Window events
State of key can be tracked using KeyListener. Keys are pressed, released, typed. To handle these events KeyListener interface is used. KeyListener is notified about the change in the state of key and action can be taken according to the state change of the key. Following methods are defined in the KeyListener:
Following program shows how to handle Key events
import java.awt.*; import java.awt.event.*; import javax.swing.*; class Keylist extends JFrame implements KeyListener { JLabel l; JTextArea area; String text = ""; public Keylist() { l = new JLabel(); l.setBounds (20, 50, 500, 20); area = new JTextArea(); area.setBounds (20, 200, 200, 200); area.addKeyListener(this); add(l); add(area); setSize(400, 600); setLayout(null); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void keyPressed (KeyEvent e) { if(e.getKeyCode() <=65 && e.getKeyCode()>=91) l.setText("Alphabet is Types"); else l.setText("It is not alphabet, it is something else: "+e.getKeyCode()); } public void keyReleased (KeyEvent e) { } public void keyTyped (KeyEvent e) { } } class KeyListenerImplements{ public static void main(String[] args) { new Keylist(); } }
We can perform some operations on window like closing window, opening window, resizing window etc. Based on the events on window, specific tasks can be performed. In Java, to handle window events, WindowListener interface is implemented. The WindowListner interface has following methods defined:
Following program shows how to handle window Events.
import java.awt.*; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.*; class Window_event_demo { public static void main(String[] args) { new WindowListener_demo(); } } class WindowListener_demo extends JFrame implements WindowListener { JLabel lbl; WindowListener_demo() { addWindowListener(this); lbl = new JLabel(""); add(lbl); lbl.setBounds(20,50,200,25); setSize (500, 500); setLayout (null); setVisible (true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void windowActivated (WindowEvent we) { lbl.setText("Window is Active"); } public void windowClosed (WindowEvent we) { lbl.setText("Window is closeddddddd"); System.out.println("Window closed!!!"); } public void windowClosing (WindowEvent we) { System.out.println("Window will be closed, it is closing"); dispose(); } public void windowDeactivated (WindowEvent we) { lbl.setText("Window is DeActive"); } public void windowDeiconified (WindowEvent we) { lbl.setText("Now window is changed to normal size from minimized size."); System.out.println("Now window is changed to normal size from minimized size."); } public void windowIconified(WindowEvent we) { lbl.setText("Now window is changed from minimized size to normal size."); System.out.println("Now window is changed from minimized size to normal size."); } public void windowOpened(WindowEvent we) { lbl.setText("Window is Opened!"); } }